package com.ruoyi.electricity.task;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.electricity.controller.UndergroundElectricitySystem;
import com.ruoyi.electricity.domain.ElectricityData;
import com.ruoyi.electricity.service.ElectricityDataService;
import com.ruoyi.rsikManage.domain.BroadCast;
import com.ruoyi.rsikManage.domain.MonitorPoint;
import com.ruoyi.rsikManage.domain.vo.BroadCastRequestVo;
import com.ruoyi.rsikManage.service.BroadcastService;
import com.ruoyi.rsikManage.service.CustomConfigurationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletContext;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Component
public class Scheduler {
    @Autowired
    private UndergroundElectricitySystem undergroundElectricitySystem;
    @Autowired
    private ElectricityDataService electricityDataService;
    @Autowired
    ServletContext servletContext;
    @Autowired
    CustomConfigurationService customConfigurationService;
    @Autowired
    BroadcastService broadcastService;
    @Value("${UNDERGROUND_ELECTRICITY_SYSTEM_SWITCH}")
    private boolean electricitySystemSwitch;
    private int count = 0;

    @Scheduled( cron = "${scheduler.electricityDataUpdateCorn}")
    @Transactional
    public void updateElectricityData() {
        if(!electricitySystemSwitch) {
            return;
        }
        System.out.println("--------------更新用电数据：" + LocalTime.now());
        String electricityDataJsonStr = undergroundElectricitySystem.getRealTimeElectricityData();
        List<ElectricityData> list = toElectricityDataList(electricityDataJsonStr);
        electricityDataService.mergeElectricityDataListToTable(list);
        electricityDataService.deleteElectricityDataNotInList(list);
        System.out.println("-------------添加用电历史-----------");
        electricityDataService.insertElectricityDataToHistoryTable(list);
        electricityDataService.insertElectricityDataToDayTable(list);
        List<ElectricityData> electricityDataList = electricityDataService.selectElectricityDataThatNeedToSendAlarm();
        if (electricityDataList != null && electricityDataList.size() > 0) {
            System.out.println("-------------加入用电报警-----------------");
            electricityDataService.insertElectricityAlarm(electricityDataList);
            System.out.println("-------------更新用电报警发送标志-----------------");
            for (ElectricityData electricityData : electricityDataList) {
                electricityDataService.updateElectricityAlarmStatusAsSent(electricityData);
            }
            //广播播报
            if(servletContext.getAttribute("broadcastPlaySwitch").equals(1)) {
                for (ElectricityData e: electricityDataList) {
                    //获取该用电设备关联的广播
                    List<BroadCast> broadcasts = broadcastService.selectEquipAssociatedBroadcasts(e.getEquipCode());
                    Integer[] broadcastIds = broadcasts.stream()
                            .map(BroadCast::getID) // 将 BroadCast 对象转换为 ID 值
                            .toArray(Integer[]::new);
                    String broadcastContent = builderBroadcastContent(e);
                    BroadCastRequestVo broadCastRequestVo = new BroadCastRequestVo(broadcastIds, broadcastContent,null,null);
                    customConfigurationService.PlayBroadcastContent(broadCastRequestVo);
                }
            }
        }
    }

    private List<ElectricityData> toElectricityDataList(String electricityDataJsonStr) {
        JSONArray jsonArray = JSONArray.parseArray(electricityDataJsonStr);
        int dataCount = jsonArray.size();
        List<ElectricityData> resList = new ArrayList<>(dataCount);
        for (int i = 0; i < dataCount; i++) {
            ElectricityData electricityData = new ElectricityData();
            JSONObject j = jsonArray.getJSONObject(i);
            electricityData.setEquipCode(j.getString("MeterID"))
                            .setEquipName(j.getString("MeterName"))
                            .setVoltage(j.getDouble("Voltage"))
                            .setCurrent(j.getDouble("Electric"))
                            .setActive(j.getDouble("FAQValue"))
                            .setPaEnergy(j.getDouble("PAEnergy"))
                            .setFactor(j.getDouble("PowerFactor"))
                            .setDataTime(j.getString("InsertTime"));
            resList.add(electricityData);
        }
        return resList;
    }

    @Scheduled(cron = "0 0 0 * * ?")
    public void deleteElectricityDataFromThirtyDaysAge() {
        if(!electricitySystemSwitch) {
            return;
        }
        electricityDataService.deleteElectricityData();
    }

    private String builderBroadcastContent(ElectricityData e) {
        StringBuilder broadcastContentBuilder = new StringBuilder(e.getEquipName());
        Double current = e.getCurrent();
        Double currentMinNormalVal = e.getCurrentMinNormalVal();
        Double currentMaxNormalVal= e.getCurrentMaxNormalVal();
        Double voltage = e.getVoltage();
        Double voltageMinNormalVal = e.getVoltageMinNormalVal();
        Double voltageMaxNormalVal = e.getVoltageMaxNormalVal();

        if (current > currentMaxNormalVal) {
            broadcastContentBuilder.append("电流高于正常范围");
        }
        if (current < currentMinNormalVal) {
            broadcastContentBuilder.append("电流低于正常范围");
        }
        if (voltage > voltageMaxNormalVal) {
            broadcastContentBuilder.append("电压高于正常范围");
        }
        if (voltage < voltageMinNormalVal) {
            broadcastContentBuilder.append("电压低于正常范围");
        }

        return broadcastContentBuilder.toString();
    }
    /*
    每日0点进行 数据库表清理
     */

    @Scheduled(cron = "0 0 0 * * ?")
    @Transactional
    public void deleteElectricityDataToDayTable() {
        electricityDataService.deleteElectricityDataToDayTable();
    }
}
